package com.Guo.system.service.impl;

import com.Guo.handler.BusinessException;
import com.Guo.response.ResultCode;
import com.Guo.system.entity.Department;
import com.Guo.system.entity.User;
import com.Guo.system.enums.UserStatusEnum;
import com.Guo.system.enums.UserTypeEnum;
import com.Guo.system.mapper.DepartmentMapper;
import com.Guo.system.mapper.UserMapper;
import com.Guo.system.service.UserService;
import com.Guo.system.vo.UserVO;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Guo
 * @since 2020-12-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Page<User> findUserPage(Page<User> page, UserVO userVO) {
        //这是获取分页的数据
        List<User> userList = this.baseMapper.findUserPage(page,userVO);
        //将刚刚通过动态sql获取的数据设置给分页的记录就行了
        return page.setRecords(userList);
    }

    @Override
    public User binding(Long id) {
        return this.baseMapper.binding(id);
    }

    @Override
    public void exportUserExcel(HttpServletResponse response, List<User> tbUsers) throws IOException {
        //----- 写入excel文件  exportFileName文件名称
        String exportFileName = "TbUserInfo.xlsx";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("用户信息")
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(tbUsers);
    }

    @Override
    public User selectByName(String userName) {
        return this.baseMapper.selectByName(userName);
    }

    @Override
    public void addUser(User user) {
        //判断是否新增了同一个用户
        String username = user.getUsername();
        //获取部门
        Long departmentId = user.getDepartmentId();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Integer count = this.baseMapper.selectCount(wrapper);
        if(count!=0){
            //账号已经存在
            throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }
        Department department = departmentMapper.selectById(departmentId);
        if(department==null){
            //返回部门为空
            throw new BusinessException(ResultCode.DEPARTMENT_NOT_EXIST.getCode(),
                    ResultCode.DEPARTMENT_NOT_EXIST.getMessage());
        }
        //设置盐值  在这里其实已经没有意义了,因为spring security加密的密码默认已经提供了盐值
        String salt= UUID.randomUUID().toString().substring(0,32);
        user.setSalt(salt);
        //使用spring security自带的密码加密策略
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //添加的用户默认是普通用户
        user.setType(UserTypeEnum.SYSTEM_USER.getTypeCode());
        //添加的用户默认启用
        user.setStatus(UserStatusEnum.AVAILABLE.getStatusCode());
        this.baseMapper.insert(user);
    }
}
